package com.testingedu.filter;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class FrontActionInvoke extends ActionInvoke {
	private static final Log log = LogFactory.getLog(FrontActionInvoke.class);
	private static final String actionConfig = "frontAction.properties";
	private static final Map<String, String> actionMapping = new HashMap<String, String>();
	static {
		init();
	}
	/**
	 * 初始化对应的配置文件
	 */
	public static void init() {
		Properties properties = new Properties();
		try {
			properties.load(FrontActionInvoke.class.getClassLoader().getResourceAsStream(actionConfig));
			Set<Object> keys = properties.keySet();
			for (Object object : keys) {
				actionMapping.put((String) object, (String) properties
						.getProperty((String) object));
			}
		}catch(Exception e) {
			System.out.println(e);
			log.error("前台初始化配置文件失败："+e);
		}
	}
	
	public void invoke() throws Exception{
		if (!baseURISecurity(4)) { // 判断url是否合法
			request.getRequestDispatcher(PAGE_404).forward(request, response);
		} else {
			String action = uris[2];// 获取将要执行的action
			String method = uris[3];// 获取将要执行的action方法名
			String className = actionMapping.get(action); // 获取action对应的类全称
			try {
				Class<?> clazz = Class.forName(className);
				Method execM = clazz.getDeclaredMethod(method+PREFIX);
				Object actionO = clazz.newInstance();
				autoEncoding();
				setReqAndRespToAction(clazz, actionO);
				setBeanToAction(clazz, actionO, null);
				try {
					execM.invoke(actionO);
					} catch (Exception e) {
						log.error("执行action时出错了：" + e);
						request.setAttribute("message", "程序执行出错了，请重试或通知管理员");
						request.getRequestDispatcher(PAGE_ERROR).forward(request,
								response);
					}
			} catch (Exception e) { // 没有对应的action或方法
				request.getRequestDispatcher(PAGE_404).forward(request, response);
			}
		}
	}
}
